﻿/*********************************************************
 * 项目：
 * 描述：
 * 作者：英夫美迪 冯东耀 simadi@qq.com
 * 日期：2012/7/4 15:59:21
 * *******************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;

namespace Common
{

    public static class Extends
    {
        /// <summary>
        /// 转换成URL参数
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static string ToQueryString(this IDictionary<object, object> dictionary)
        {
            var sb = new StringBuilder();
            foreach (var key in dictionary.Keys.Where(key => dictionary[key] != null))
            {
                sb.Append(key + "=" + dictionary[key] + "&");
            }
            return sb.ToString().TrimEnd('&');
        }
        #region 字符串格式化
        public static string ToFormat(this string str, params object[] args)
        {
            return string.Format(str, args);
        }
        #endregion

        #region Json转换对象
        public static T ToEntity<T>(this string str) where T : class
        {
            return str==null?null: DeserializeToObj<T>(str);
        }

        #endregion

        #region Json→T
        public static T DeserializeToObj<T>(string jsonString)
        {
            //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
            string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            var matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(p);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                var ser = new DataContractJsonSerializer(typeof(T));
                T obj = (T)ser.ReadObject(ms);
                return obj;
            }
        }
        #endregion
        /// <summary>
        /// 将日期字符串 转换为json的日期 1970-01-01直指定日期间的秒数
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            return string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
        }
    }
}
